package com.feinno.module.security.web;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.feinno.framework.common.web.AbstractEntityController;
import com.feinno.framework.common.web.support.JsonResult;
import com.feinno.module.security.domain.Menu;
import com.feinno.module.security.domain.Portallet;
import com.feinno.module.security.domain.Resource;
import com.feinno.module.security.domain.User;
import com.feinno.module.security.service.MenuService;
import com.feinno.module.security.service.PortalletService;
import com.feinno.module.security.service.UserService;
import com.feinno.module.security.web.support.MenuView;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 系统功能，用户认证通过后可以访问的默认资源 包括：授权功能菜单，修改密码，查看个人的信息等
 * 
 * @author zhangpu
 */

@Controller
@RequestMapping(value = "/manage/system/")
public class SystemController extends
		AbstractEntityController<User, UserService> {

	@Autowired
	private UserService userService;

	@Autowired
	private MenuService menuService;
	@Autowired
	private PortalletService portalletService;

	/**
	 * 授权功能菜单
	 * 
	 * @return
	 */
	@RequestMapping("authorisedMenus")
	@ResponseBody
	public List<MenuView> authorisedMenus() {
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		Map<Long, Menu> menus = Maps.newLinkedHashMap();
		List<Resource> resources = new LinkedList<Resource>();
		List<Object> list = menuService.queryAuthorisedMenus(user.getId());
		Iterator<Object> ie = list.iterator();
		while (ie.hasNext()) {
			Object[] obj = (Object[]) ie.next();
			resources.add((Resource) obj[0]);
			Menu menu = (Menu) obj[1];
			menus.put(menu.getId(), menu);
		}

		List<MenuView> menuViews = new LinkedList<MenuView>();
		for (Map.Entry<Long, Menu> entry : menus.entrySet()) {
			Menu menu = entry.getValue();
			MenuView menuView = new MenuView(menu.getId(), menu.getName(),
					menu.getIcon());
			for (Resource resource : resources) {
				if (resource.getMenu().getId().equals(menu.getId())
						&& "URL".equalsIgnoreCase(resource.getResType())) {
					MenuView resourceView = new MenuView(menu.getId() * 100
							+ resource.getId(), resource.getName(),
							resource.getIcon());
					resourceView.getAttributes().put("url",
							resource.getResString());
					resourceView.getAttributes().put("loadMode",
							String.valueOf(resource.getShowMode()));
					menuView.getChildren().add(resourceView);
				}
			}
			menuViews.add(menuView);
		}
		return menuViews;
	}

	@RequestMapping(value = "portallets")
	@ResponseBody
	public List<Portallet> portallets(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			return portalletService.getAll();
		} catch (Exception e) {
			return Lists.newArrayList();
		}
	}

	@RequestMapping(value = "changePassword")
	@ResponseBody
	public JsonResult changePassword(Model model, HttpServletRequest request,
			HttpServletResponse response) {
		String orginalPassword = request.getParameter("password");
		String newPassword = request.getParameter("newPassword");

		JsonResult result = new JsonResult();
		try {
			User user = (User) SecurityUtils.getSubject().getPrincipal();
			if (user != null) {
				boolean checkResult = userService.validatePassword(user,
						orginalPassword);
				if (checkResult) {
					userService.changePassword(user, newPassword);
				} else {
					throw new RuntimeException("原始密码错误");
				}
			} else {
				throw new RuntimeException("当前用户会话过期，未找到对应用户");
			}
			result.setMessage("密码修改成功");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setCode(e.getClass().toString());
			result.setMessage(e.getMessage());
		}
		return result;
	}

}
